<template>
  <div class="page">
    <div class="normal-client-main" :style="containerHeight">
      <group class="crm-form-group">
        <x-input :class="{'weui-cell_warn': errors.parent_name }"
        title="家长姓名" v-model="client.parent_name" required
        placeholder="请输入家长姓名" novalidate
        :icon-type="iconType"
        :show-clear="false" @on-blur="onBlur" placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>家长姓名</span>
        </x-input>
        <x-input :class="{'weui-cell_warn': errors.mobile_num }" ref="phone" title="手机号码" :is-type="validatePhone" v-model="client.mobile_num" placeholder="输入手机号码" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>手机号码</span>
        </x-input>
        <x-input :class="{'weui-cell_warn': errors.address }" class="address" title="所在地址" v-model="address" placeholder="请输入地址" raw-value placeholder-align="right">
          <span slot="label"><i class="require-mark">*</i>所在地址</span>
        </x-input>
        <cell title="选择地址">
          <region-picker ref="addressPicker" v-model="regionValue" :data="regions"></region-picker>
        </cell>
        <selector :class="{'weui-cell_warn': errors.source_id }" 
        direction="rtl" title="客户来源" 
        placeholder="请选择客户来源" 
        :options="clientSourceOptions" 
        v-model="client.source_id"
        @change.native="(e) => changeSource(e.target.value)" 
        placeholder-align="right" 
        >
        </selector>
          <!-- <span slot="label"><i class="require-mark">*</i>客户来源</span> -->
        <selector direction="rtl"
          title="客户二级来源" placeholder="请选择"
          :options="secondSourceOptions" v-model="client.second_source_id"
          placeholder-align="right" >
          <!-- <span slot="label"><i class="require-mark">*</i>客户来源</span> -->
        </selector>

        <selector direction="rtl"  title="渠道" placeholder="请选择渠道"
                  :options="clientChannelOptions" v-model="client.channel_id"
                  placeholder-align="right" >
          <!-- <span slot="label"><i class="require-mark">*</i>渠道</span> -->
        </selector>
        <!-- <x-input :class="{'weui-cell_warn': errors.parent_industry }" title="所属行业" placeholder="请填写所属行业" :options="industryOptions" v-model="client.parent_industry" placeholder-align="right"></x-input> -->

        <!-- <selector direction="rtl" title="客户来源" placeholder="请选择客户来源" :options="clientSourceOptions" v-model="client.source_id" placeholder-align="right" >
          <span slot="label"><i class="require-mark">*</i>客户来源</span>
        </selector> -->
        <!-- <selector direction="rtl" title="跟进状态" :options="customStatusOptions" v-model="client.custom_status" placeholder-align="right" >
          <span slot="label"><i class="require-mark">*</i>跟进状态</span>
        </selector> -->
        <selector direction="rtl" title="客户属性" placeholder="请选择客户属性" :options="customPropertyOptions" v-model="client.custom_property" placeholder-align="right" >
          <span slot="label"><i class="require-mark">*</i>客户属性</span>
        </selector>
        <selector direction="rtl" title="分配目标" placeholder="请选择分配目标" :options="reassignOptions" v-model="teamId" placeholder-align="right" >
          <span slot="label"><i class="require-mark">*</i>分配</span>
        </selector>
        <selector v-if="teamId && teamId !== -1" direction="rtl" title="分配顾问" placeholder="请选择分配顾问" :options="conselorsOptions" v-model="client.suid" placeholder-align="right" >
          <span slot="label"><i class="require-mark">*</i>指定顾问</span>
        </selector>
        <x-input required
         v-model="client.qq_num"
        placeholder="请输入QQ号" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">QQ号</span>
        </x-input>
        <x-input
         v-model="client.wechat_num"
        placeholder="请输入微信号" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">微信号</span>
        </x-input>
        <x-input
         v-model="client.remark"
        placeholder="请输入备注" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">备注</span>
          </x-input>
        <!-- <x-input :class="{'weui-cell_warn': errors.address }" title="详细地址" placeholder="请输入详细地址" v-model="client.address" placeholder-align="right"></x-input> -->
        <cell title="创建人" placeholder="输入创建人" novalidate :icon-type="iconType" v-model="client.creator" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></cell>
      </group>
      <!-- <input v-validate="'required'" name="test" /> -->
      <div class="weui-cells-no-margin" v-for="(baby, index) in this.babies" :key="index">
        <div class="weui-cells__title"  slot="after-title">
          宝宝: {{ baby.baby_name }}
          <span class="delete-baby" @click="deleteBaby(index)">删除</span>
        </div>
        <group >
          <x-input :class="{'weui-cell_warn': typeof errors.babies[index] !== 'undefined' && errors.babies[index].baby_name }" title="宝宝姓名" v-model="baby.baby_name" placeholder="输入宝宝姓名" placeholder-align="right"  :show-clear="false" @on-blur="onBlur" ></x-input>
          <selector v-validate="'required'" name="experience_time" direction="rtl" title="宝宝性别" v-model="baby.baby_sex" placeholder="输入宝宝性别"  :options="babyGenderOptions" placeholder-align="right"></selector>
          <cell title="出生日期">
            <datetime confirmText="完成" :start-date="startDate" :end-date="endDate" cancelText="取消"title="宝宝生日" v-model="baby.baby_birthday" @change="changeBirthday(baby)" placeholder="请选择宝宝生日" placeholder-align="left"></datetime>
          </cell>
        </group>
      </div>

      <edit-family
      :values="this.client.family"
      @on-change="onFamilyChange"
      ref="editFamily"></edit-family>

      <div class="btn-group center-btn-group">
        <span class="btn scrm-default-btn add-new-btn pull-left" @click="addBaby">+新增宝宝</span>
        <span class="btn scrm-default-btn save-btn pull-right" @click="saveClientInfo">保存</span>
      </div>
    </div>

    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  var dateFormat = require('dateformat')
  // import clientMenu from '../components/client-menu'
  import {showDialog, hideDialog} from '../lib/dialog'
  // import {XInput, Group, ChinaAddressData, XAddress, Selector, Datetime, Cell} from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import Cell from 'vux/src/components/cell'
  // import XAddress from 'vux/src/components/x-address'
  import ChinaAddressData from 'vux/src/datas/china_address.json'
  import Selector from 'vux/src/components/selector'
  import Datetime from 'vux/src/components/datetime'
  import XDialog from 'vux/src/components/x-dialog'
  import { DatePicker } from 'element-ui'
  import RegionPicker from 'region-picker'
  import data from 'region-picker/src/components/data.json'

  import store from '../store'
  // import {XDialog} from 'vux'
  import VeeValidate from 'vee-validate'
  import { validateClient } from '../lib/validate-rules'
  import { mapActions } from 'vuex'
  import EditFamily from '../components/edit-family';

  Vue.use(VeeValidate)

  export default {
    data () {
      var d = new Date()
      var month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
      var day = d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate()
      var str = d.getFullYear() + '-' + month + '-' + day

      return {
        containerHeight: 'min-height:' + document.body.scrollHeight + 'px;',
        regionValue: [],
        endDate: str,
        teamId: -1,
        defaultTeamId: '',
        startDate: '1990-01-01',
        reassignOptions: [],
        conselorsOptions: [],
        secondSourceOptions: [],
        regions: data,
        client: {
          "id": '',
          "site_id": null,
          "custom_type": "PT#",
          "uniacid": null,
          "open_id": null,
          "union_id": null,
          "nick_name": null,
          "sex": '0',
          "head_img_url": '',
          "subscribe_time": null,
          "remark": null,
          "province": null,
          "subscribe": null,
          "mobile_num": null,
          "parent_name": null,
          "city": '广州市',
          "district": "番禺区",
          "custom_status": "NC#",
          "custom_property": "YB#",
          "suid": null,
          "uid": null,
          "is_distribute": 1,
          "status": "OK##",
          "backup_mobile_num": null,
          "parent_type": null,
          "telephone": null,
          "parent_industry": null,
          "parent_job": null,
          "source": '',
          "source_id": '',
          "second_source_id": '',
          "channel_id":"",
          "last_contact_time": null,
          "insert_time": "2017-03-22 15:46:35",
          "update_time": null,
          "operator_id": null
        },
        baby: {
          baby_sex: 'MALE###',
          baby_name: '',
          baby_birthday : new Date().toLocaleDateString()
        },
        babies:[],
        iconType: '',
        addressData : ChinaAddressData,
        errors: {
          babies: {}
        },
        address: '',

        // source_id: '',
        // parent_industry: '',
        // babyGenderValue: '',

        babyGenderOptions: [
        {
          key : 'MALE###',
          value: '男'
        },
        {
          key: 'FEMALE#',
          value: '女'
        }
        ],

        industryOptions : [

        {
          key: 'IT',
          value:'IT软件业'
        },

        {
          key:'hairdressing',
          value:'美容美甲'}
        ],

        clientSourceOptions: [],
        clientChannelOptions:[],

        followStatus : [

        {
          key: 'followed',
          value:'已跟进'
        },

        {
          key:'unfollowed',
          value:'未跟进'}
        ],

        followProperties : [

        {
          key: 0,
          value:'意向客户'
        },

        {
          key:1,
          value:'我的客户'
        }
        ],
      }
    },
    components: {
      'datetime': DatePicker,
      XInput,
      Group,
      [RegionPicker.name]: RegionPicker,
      Selector,
      // Datetime,
      Cell,
      XDialog,
      EditFamily
    },
    methods: {
      ...mapActions({
        getChildSource: 'getChildSource',
        getDefaultAddress: 'getDefaultAddress',
        getCounsellors: 'getCounsellors',
      }),
      async changeSource (sourceId, refresh) {
        if (refresh !== false) this.client.second_source_id = ''
        const response = await this.getChildSource({id: sourceId})
        if (response.errcode === 0) {
          let results = response.results;
          let secondSourceOptions = []
          results.forEach((elem) => {
            secondSourceOptions.push({key: elem.id, value: elem.source_name})
          })
          this.secondSourceOptions = secondSourceOptions
        } else {
          this.secondSourceOptions = []
        }
      },
      initAddress () {
        this.getDefaultAddress({team_id: this.defaultTeamId})
          .then((response) => {
            if (response.data.errcode === 0) {
              if (!this.address) {
                this.address = response.data.results.address
              }
            }
          }).catch((e) => {
            console.log(e)
          })
      },
      changeBirthday (baby) {
        baby.baby_birthday = dateFormat(baby.baby_birthday, 'yyyy-mm-dd')
        if (this.endDate && this.endDate < baby.baby_birthday) {
          showDialog('出生日期必须不能超过今天')
          baby.baby_birthday = ''
          return
        }
      },
      validatePhone (phone) {
        if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone))){
          console.log('phone unavalible')
          return {valid:false}
        }
        console.log('phone avalible')
        return {valid:true}
      },
      deleteBaby (baby, index) {
        if(this.babies.length>1) {
          this.babies.splice(index, 1)
        } else {
          console.log(this.custom_type, 'ssss')
          if(this.custom_type === 1) {
            showDialog('必须保留一个宝宝喔!');
            setTimeout(() => {   hideDialog() },3300)
          } else {
            this.babies = []
          }
        }
      },
      refresh (iscroll) {
        console.log('refresh')
        // Refresh current data
      },

      hideDialog: hideDialog,

      log(){
        console.log('ee');
      },

      validate () {
        this.errors = validateClient(this.client, this.babies)
        console.log(this.$el)
        return !!this.$el.getElementsByClassName('weui-cell_warn').length
      },

      load (iscroll) {
        console.log('load')
      // Load new data
      },

      test(){
        console.log('test')
      },

      onBlur(){

      },

      onShow(){
        console.log(arguments)
      },

      addBaby(){
        let newBaby = Object.assign({}, this.baby)
        this.babies.push(newBaby);
      },

      validate () {
        console.log(this.$el, this.$el.getElementsByClassName('weui-cell_warn').length, 'this.$el.getElementsByClassName().length')
        return this.$el.getElementsByClassName('weui-cell_warn').length === 0
      },
      //初始化客户信息
      initClientInfo(id){

        if(!this.clientsDetail[id]) {
          store.dispatch('getCustomInfoById', id);
        }

        let client = this.clientsDetail[id];
        this.client = Object.assign(this.client, client);
        this.client.address = [this.client.province, this.client.city, this.client.district];
        this.id = id;

        console.log(JSON.stringify(client), 'client');
      },

      initBabyInfo(id) {
      },


      submit () {
        let that = this;

        const editFamilyValidator = this.$refs.editFamily.$v
        editFamilyValidator.members.$touch()

        if (editFamilyValidator.$error === true) {
          return ;
        }

        if(this.validate() === false) {
          showDialog('保存信息有误，请查看文字标红部分!')
          return ;
        }

        if(this.saveLock) {
          showDialog('提交中....');
          setTimeout(() => {   hideDialog() },300)
          return ;
        }
        let data = that.client

        if (data.custom_status === "0") {
          data.custom_status = null
          showDialog('请选择跟进状态');
          setTimeout(() => {   hideDialog() }, 2300)
          return
        }
        if (data.source_id === "0") {
          data.source_id = null
          showDialog('请选择客户来源');
          setTimeout(() => {   hideDialog() }, 2300)
          return
        }

        this.saveLock = true
        data.babys = that.babies
        store.dispatch('saveClientInfo', data).then(function(aresponse){
          if(aresponse.data.errcode == 0) {
            that.saveLock = false
            const customId = aresponse.data.results.id
            showDialog(aresponse.data.errmsg)

            setTimeout(() => {
              hideDialog();
              that.$router.push({name: 'normal-client', query: {custom_id: customId, id: customId, custom_type: 1, activeItem:'marketing' }})
              // that.$router.back()
            }, 2000)
          } else {
            showDialog(aresponse.data.errmsg)
            console.log('保存客户信息失败!', JSON.stringify(aresponse.data))
          }
          that.saveLock = false
        }).catch((error) =>{
          console.log(error)
          that.saveLock = false
        });
      },

      saveClientInfo(){
        this.errors = validateClient(this.client, this.babies)
        setTimeout(() => {
          this.submit()
        })
      },
      findNameByAddressId (id) {
        let name = ''
        this.addressData.forEach((region) => {
          if (region.value === id) {
            name = region.name
          }
        })
        return name
      },
      initConselorsOptions (teamId) {
        teamId = teamId || this.teamId
        this.getCounsellors({team_id: teamId}).then((response) => {
          if (response.data.errcode === 0) {
            const conselors = response.data.results
            let options = [{key: '', value: '不限'}]
            if (conselors) {
              for (let id in conselors) {
                options.push({key: id, value: conselors[id]})
              }
              this.conselorsOptions = options
            }
          }
        })
      },
      initReassignSetting () {
        const teamList = this.loginUser.my_team_list
        let reassignOptions = []
        for (let teamId in teamList) {
          let teamName = teamList[teamId]
          reassignOptions.push({ value: teamName, key: teamId })
        }
        this.reassignOptions = reassignOptions
      },
      onFamilyChange (families) {
        this.client.family = families
      },
      handleOtherSource (client) {
        console.log(client, 'handleOtherSource')
        if (client.redirect_sys === 'xiaochengkefu') {
          this.client.remark = client.remark_name
          this.client.parent_name = client.real_name
          this.client.mobile_num = client.phone
        }
      },
      isNumber(value) {
        let formatedInt = parseInt(value)
        return isNaN(formatedInt) ? false : (typeof formatedInt === 'number' ? true : false)
      }
    },

    mounted () {
      let query = this.$route.query
      console.log(query, 'query')
      this.custom_type = query.custom_type
      let defaultTeam = Object.keys(this.loginUser.my_team_list)
      this.defaultTeamId = defaultTeam.length ? defaultTeam[0] : ''

      if (!this.client.address && this.defaultTeamId) {
        this.teamId = this.defaultTeamId
        this.client.suid = this.loginUser.id
        this.initAddress()
      }

      this.client.custom_type = parseInt(this.custom_type) === 1 ? 'QT#' : 'WX#'
      this.client.creator = this.loginUser.name

      this.addBaby()
      this.initReassignSetting()
      if (query.redirect_sys) {
       this.handleOtherSource(query)
      }
      this.callJsApi('biz.navigation.setTitle', {title: '新增客户'})
    },

    beforeMount () {
      store.dispatch('getCustomSource')
      store.dispatch('getChannel')
    },

    watch: {
      customSources () {
        let customSources = this.customSources
        for (let id in customSources) {
          let source = customSources[id]
          this.clientSourceOptions.push({
            key: id,
            value: source
          })
        }

        if (this.clientSourceOptions.length) {
          let sourceId = false
          if (!this.isNumber(this.client.source_id)) {
            sourceId = this.clientSourceOptions[0].key
          } else {
            sourceId = this.client.source_id
          }

          this.changeSource(sourceId, false)
        }
      },
      channel () {
        let channel_list = this.channel
        console.log(channel_list)
        for (let id in channel_list) {
          let info = channel_list[id]
          this.clientChannelOptions.push({
            key: id,
            value: info
          })
        }
      },
      teamId (val) {
        this.conselorsOptions = []
        if (val !== -1) {
          this.client.team_id = val
          this.initConselorsOptions(val)
        } else if (this.client.team_id) {
          delete this.client.team_id
        }
      },
      // regionValue (regions) {
      //   this.client.province = this.findNameByAddressId(regions[0])
      //   this.client.city = this.findNameByAddressId(regions[1])
      //   this.client.district = this.findNameByAddressId(regions[2])
      // },
      location (location) {
        this.client.district = this.location.clue_location
      },
      address (address) {
        this.client.address = address
      },
      regionValue (value) {
        const regionPickerElem = this.$refs.addressPicker.$el
        const addressText = this.$refs.addressPicker.$children[0].selected.fullName.replace(/\s/g, '')
        const addressArr = addressText.split('/')
        if (!addressArr) {
          return showDialog('请选择地址！')
        }

        if (addressArr.length < 3) {
          showDialog('请选择区域！')
          addressArr[2] = ''
        }
        if (addressArr.length < 2) {
          return showDialog('请选择市区！')
        }
        this.client.province = addressArr[0]
        this.client.city = addressArr[1]
        this.client.district = addressArr[2]
        this.client.address = addressArr.join('')
        this.address = addressArr.join('')
      }
    },
    computed : {
      //包含客户详情的列表
      clientsDetail(){
        return this.$store.state.app.clientsDetail;
      },

      //跟进状态选项列表
      customStatusOptions() {
        return [{key:0, value: '请选择跟进状态'}].concat(this.$store.state.app.customStatusOptions);
      },

      //客户属性选项列表
      customPropertyOptions() {
        return this.$store.state.app.customPropertyOptions;
      },

      loginUser () {
        return this.$store.state.app.user;
      },

      customSources () {
        return Object.assign(this.$store.state.app.customSources);
      },

      channel () {
        return Object.assign(this.$store.state.app.channel)
      }
    }

  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .normal-client-main{

    .crm-form-group {
      &>.weui-cells {
        overflow: initial;
      }

      .region-picker .picker-menu {
        right: 0px;
      }
    }

    .no-margin{
       &>*{
       margin: 0
       }
    }

    .add-new-btn{
      width: 60%;
    }

    .btn-group{
      &:extend(.clearfix all);
      margin-top: 15px;


      &>*{
        width: 38%;
        text-align: center;
        border-radius: 4px;
        padding: 10px;
        margin: 0 8px;
      }

      .pull-left{
      float: left;
      }

      .pull-right{
      float: right;
      }
    }

    .weui-select{
      text-align: right!important;
    }

    .babayArea>.weui-cell:before {
      content: " ";
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      height: 1px;
      /* border-top: 1px solid #D9D9D9; */
      color: #D9D9D9;
      -webkit-transform-origin: 0 0;
      transform-origin: 0 0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
      left: 15px;
    }

    .delete-baby {
      float: right;
      color: #39ADFF;
    }


  }
</style>
